/*eslint no-console: ["error", { allow: ["warn", "error", "log"] }] */
/* global phantom, document */

var page = require('webpage').create()
var system = require('system')

var url = system.args[1] ? system.args[1] : null
var code = system.args[2] ? system.args[2] : null

page.open(url, function(status) {
    if (status !== 'success') {
        console.log('打开' + url + '失败')
    } else {
        var result = page.evaluate(function(code) {
            var getCode = document.querySelector('#J_GetCode')
            if (!getCode) {
                return false
            }

            if (!code) {
                getCode.click()
            } else {
                document.querySelector('#J_Checkcode').value = code
                document.querySelector('[type=submit]').click()
            }
            return true
        }, code)

        if (result !== true) {
            console.log('页面已失效')
        }
    }
    phantom.exit()
})
